package com.example.wuqujingdianphone.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wuqujingdianphone.R;
import com.example.wuqujingdianphone.activity.BookDetailActivity;
import com.example.wuqujingdianphone.activity.BookReadActivity;
import com.example.wuqujingdianphone.activity.LoginActivity;
import com.example.wuqujingdianphone.adapter.BRBookAdapter;
import com.example.wuqujingdianphone.api.GlobalConfig;
import com.example.wuqujingdianphone.base.BaseFragment1;
import com.example.wuqujingdianphone.bean.BookHomeListBean;
import com.example.wuqujingdianphone.bean.BookListBean;
import com.example.wuqujingdianphone.utils.Message1Event;
import com.example.wuqujingdianphone.utils.NetWorkHelper;
import com.example.wuqujingdianphone.utils.NiceDialogUtils;
import com.example.wuqujingdianphone.utils.SPUtil;
import com.example.wuqujingdianphone.utils.ToastUtil;
import com.othershe.nicedialog.NiceDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.mode.CacheMode;
import com.vise.xsnow.http.mode.CacheResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by yuanpk on 2018/4/9.
 * 书架---图书
 */

public class BRBookFragment extends BaseFragment1 implements OnRefreshListener {
    private static final String TAG = "BRBookFragment";
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    Unbinder unbinder;

    @BindView(R.id.login_to)
    TextView loginTo;

    @BindView(R.id.title)
    TextView title;
    private BRBookAdapter mAdapter;

    @BindView(R.id.no_login_dd)
    LinearLayout noLoginDd;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private int page = 1;

    public static BRBookFragment getBRBookFragment() {
        BRBookFragment fragment = new BRBookFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_rack_book, null);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        title.setText("书架");
        initView();
        initData(page);
        return view;
    }

    private void initView() {
        if (SPUtil.getBoolean(getActivity(), "isLogin", false)) {
            refreshLayout.setVisibility(View.VISIBLE);
            noLoginDd.setVisibility(View.GONE);
            showLoading(getActivity());
        } else {
            refreshLayout.setVisibility(View.GONE);
            noLoginDd.setVisibility(View.VISIBLE);
        }
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mAdapter = new BRBookAdapter(getActivity(), null);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);

        loginTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), LoginActivity.class));
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i(TAG, "onItemClick: position=" + position);
                /*Intent intent = new Intent(getActivity(), BookDetailActivity.class);
                intent.putExtra("bookId", mAdapter.getItem(position).id);
                intent.putExtra("bookTitle", mAdapter.getItem(position).title);
                startActivity(intent);*/

              /*  Intent intent = new Intent(getActivity(), BookReadActivity.class);
                intent.putExtra("pdfurl",mAdapter.getItem(position).spic);
                startActivity(intent);*/
                getDataFromService1(mAdapter.getItem(position).pid);

            }
        });

        //refresh
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableAutoLoadmore(false);
        refreshLayout.setEnableScrollContentWhenLoaded(false);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        //refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()).setSpinnerStyle
             //   (SpinnerStyle.Translate).setTextSizeTitle(14));
        refreshLayout.setOnRefreshListener(this);
    }


    private void getDataFromService1(String id) {

        //获取图书列表数据
        ViseHttp.GET("index.php/Jiekou/show/id/" + id)
                .tag(TAG)
                .request(new ACallback<BookHomeListBean>() {
                    @Override
                    public void onSuccess(BookHomeListBean data) {
                        Intent intent = new Intent(getActivity(), BookDetailActivity.class);
                        intent.putExtra("bookId", data.id);
                        intent.putExtra("bookTitle", data.news_tit);
                        intent.putExtra("fromwhere", 101);
                        startActivity(intent);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtil.show("获取书籍失败了，请重试！");
                    }
                });


    }

    private void initData(final int mPage) {
        // NiceDialogUtils.showNiceDialog(getChildFragmentManager());

        String account = SPUtil.getString(getActivity(), GlobalConfig.ACCOUNT_KEY, "");
        Log.i(TAG, "initData: account=" + account);
        ViseHttp.GET("index.php/Jiekou/collet/mobile/" + account)//account
                .tag(TAG)

                .request(new ACallback<List<BookListBean>>() {
                    @Override
                    public void onSuccess(List<BookListBean> bookListBeen) {
                        //  NiceDialogUtils.dismissNiceDialog();
                        //请求成功，AuthorModel为解析服务器返回数据的对象，可以是String，按需定义即可
                        cancelLoading();
                        if (bookListBeen != null && bookListBeen.size() > 0) {
                            Log.i(TAG, "onSuccess: bookListBeen.size()=" + bookListBeen.size());
                            mAdapter.setNewData(bookListBeen);
                        } else {
                            mAdapter.setNewData(null);
                            mAdapter.setEmptyView(R.layout.comment_empty_view, (ViewGroup) mRecyclerView.getParent());
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        cancelLoading();
                        //请求失败，errCode为错误码，errMsg为错误描述
                        // ToastUtil.showToast("errCode=" + errCode + " errMsg=" + errMsg);
                    }
                });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMsgEvent(Message1Event messageEvent) {
        String msg = messageEvent.getMsg();
        if (msg.equals(GlobalConfig.LOGIN_IS_OK)) {
            refreshLayout.setVisibility(View.VISIBLE);
            noLoginDd.setVisibility(View.GONE);
            showLoading(getActivity());
            initData(page);
        }

        if (msg.equals(GlobalConfig.LOG_OUT)) {
            refreshLayout.setVisibility(View.GONE);
            noLoginDd.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh(final RefreshLayout refreshlayout) {
        refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (NetWorkHelper.isConnected(getContext())) {
                    page = 1;
                    initData(page);
                    refreshLayout.finishRefresh();
                    refreshLayout.resetNoMoreData();//恢复上拉状态
                } else {
                    refreshLayout.finishRefresh(false);
                    refreshLayout.resetNoMoreData();
                    ToastUtil.showToast("网络加载失败了！");
                }

            }
        }, 800);
    }

//    @Override
//    public void onLoadmore(RefreshLayout refreshlayout) {
//        refreshLayout.getLayout().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (NetWorkHelper.isConnected(getContext())) {
//                    page++;
//                    initData(page);
//                    refreshLayout.finishLoadmore();
//                } else {
//                    refreshLayout.finishLoadmore(false);
//                    ToastUtil.showToast("网络加载失败了!");
//                }
//            }
//        }, 500);
//    }
}




